﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Data;
using System.Drawing;
using Infragistics.WebUI.UltraWebGrid;

public partial class SplitPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESRejectAppBusiness rejectapp = new uMESRejectAppBusiness();

    string businessName = "批次管理", parentName = "Container";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Dictionary<string, string> popupData = (Dictionary<string, string>)Session["PopupData"];
            txtDispProcessNo.Text = popupData["ProcessNo"].ToString();
            txtDispOprNo.Text = popupData["OprNo"].ToString();
            txtDispContainerID.Text = popupData["ContainerID"].ToString();
            txtDispContainerName.Text = popupData["ContainerName"].ToString();
            txtDispProductName.Text = popupData["ProductName"].ToString();
            txtDispDescription.Text = popupData["Description"].ToString();
            txtDispContainerQty.Text = popupData["Qty".ToString()].ToString();
            //txtDispPlannedStartDate.Text = popupData["PlannedStartDate"].ToString();
            //txtDispPlannedCompletionDate.Text = popupData["PlannedCompletionDate"].ToString();

            txtPlannedstartdate.Value = Convert.ToDateTime(popupData["PlannedStartDate"]).ToString("yyyy-MM-dd");
            txtPlannedcompletiondate.Value =Convert.ToDateTime(popupData["PlannedCompletionDate"]).ToString("yyyy-MM-dd");
            txtChildCount.Text = popupData["ChildCount"].ToString();
            txtDispWorkflowID.Text = popupData["WorkflowID"].ToString();

            Session["PopupData"] = null;
            Session["ContainerMessage"] = null;
            string strChildCount = txtChildCount.Text;

            int intLevel = 1;
            common.ContainerSplitLevel(txtDispContainerID.Text, ref intLevel);
            txtLevel.Text = intLevel.ToString();

            txtTime.Text = common.ContainerSplitTime(txtDispContainerID.Text).ToString();

            if (strChildCount == "0")
            {
                tdNo.Visible = false;
            }
            else
            {
                tdQty.Visible = false;

                string strContainerID = txtDispContainerID.Text;
                DataTable dtProductNo = common.GetProductNo(strContainerID);

                if (txtLevel.Text == "1")
                {
                    txtNewContainerName.Text = txtDispContainerName.Text + "-" + txtTime.Text.PadLeft(2, '0');
                }

                if (txtLevel.Text == "2")
                {
                    txtNewContainerName.Text = txtDispContainerName.Text + "-" + txtTime.Text;
                }

                if (txtLevel.Text == "3")
                {
                    char a = (char)(int.Parse(txtTime.Text)-1 + 65);
                    txtNewContainerName.Text = txtDispContainerName.Text + a;
                }

                wgProductNoList.DataSource = dtProductNo;
                wgProductNoList.DataBind();
            }

            hdSuccess.Value = "";
            //txtScrapInfoName.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        }
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }
    #endregion

    #region 提交按钮
    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);
   

        try
        {
            if (int.Parse(txtLevel.Text) > 3)
            {
                ShowStatusMessage("只允许到3级拆分!", false);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtPlannedstartdate.Value) || string.IsNullOrWhiteSpace(txtPlannedcompletiondate.Value))
            {
                ShowStatusMessage("批次的计划开始和完成时间需同时存在", false);
                return ;
            }

            string strChildCount = txtChildCount.Text;
            string splitContainers = "";
            if (strChildCount == "0")
            {
                //新批次列表
                DataTable dtChildContainer = new DataTable();
                dtChildContainer.Columns.Add("ContainerName");
                dtChildContainer.Columns.Add("Qty");
                int intSplitQty = 0;
                for (int i = 0; i < wgChildContainers.Rows.Count; i++)
                {
                    DataRow row = dtChildContainer.NewRow();

                    if (wgChildContainers.Rows[i].Cells.FromKey("ContainerName").Value != null)
                    {
                        row["ContainerName"] = wgChildContainers.Rows[i].Cells.FromKey("ContainerName").Value.ToString();
                    }
                    else
                    {
                        row["ContainerName"] = string.Empty;
                    }

                    if (wgChildContainers.Rows[i].Cells.FromKey("Qty").Value != null)
                    {
                        row["Qty"] = wgChildContainers.Rows[i].Cells.FromKey("Qty").Value.ToString();
                    }
                    else
                    {
                        row["Qty"] = "0";
                    }

                    if (Convert.ToInt32(row["Qty"]) == 0) {
                        ShowStatusMessage("批次数量不能为0", false);
                        return;
                    }
                    intSplitQty += int.Parse(row["Qty"].ToString());
                    splitContainers += wgChildContainers.Rows[i].Cells.FromKey("ContainerName").Text+",";
                    dtChildContainer.Rows.Add(row);
                }

                if (intSplitQty >= int.Parse(txtDispContainerQty.Text))
                {
                    ShowStatusMessage("子批次数量之和须小于主批次数量", false);
                    return;
                }

                //拆批
                Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
                string strOprEmployeeID = userInfo["EmployeeID"];
                string strEmployeeName = userInfo["EmployeeName"];
                string strPassword = userInfo["Password"];
                string strContainerName = txtDispContainerName.Text;
                string strNewContainerName = txtNewContainerName.Text.Trim();
                Dictionary<string, object> para1 = new Dictionary<string, object>();
                para1.Add("ContainerName", strContainerName);
                para1.Add("ServerUser", userInfo["ApiEmployeeName"]);
                para1.Add("ServerPassword", userInfo["ApiPassword"]);

                DataTable dtToContainerInfo = new DataTable();
                dtToContainerInfo.Columns.Add("ToContainerName");
                dtToContainerInfo.Columns.Add("Qty");
                dtToContainerInfo.Columns.Add("PlannedStartDate");
                dtToContainerInfo.Columns.Add("PlannedCompletionDate");



                foreach (DataRow row in dtChildContainer.Rows)
                {
                    DataRow rowToContainer = dtToContainerInfo.NewRow();
                    rowToContainer["ToContainerName"] = row["ContainerName"].ToString();
                    rowToContainer["Qty"] = row["Qty"].ToString();
                    rowToContainer["PlannedStartDate"] = txtPlannedstartdate.Value;
                    rowToContainer["PlannedCompletionDate"] = txtPlannedcompletiondate.Value;

                    dtToContainerInfo.Rows.Add(rowToContainer);
                }

                para1.Add("dtToContainerInfo", dtToContainerInfo);

                DataTable dtChildList = new DataTable();
                dtChildList.Columns.Add("ContainerName");
                dtChildList.Columns.Add("Level");

                para1.Add("dtChildList", dtChildList);

                string strMessage = string.Empty;
                Boolean result;
                if (hdSuccess.Value=="")
                {
                    result = rejectapp.SplitContainer(para1, out strMessage);

                    if (result == false)
                    {
                        ShowStatusMessage(strMessage, false);
                        return;
                    }
                    hdSuccess.Value = "Success";
                }
                if (hdSuccess.Value == "Success")
                {
                    //修改批次计划开始结束时间
                    result = rejectapp.ContainerMaint(para1, ref strMessage);

                    if (result == false)
                    {
                        ShowStatusMessage(strMessage, false);
                        return;
                    }
                }

            }
            else
            {
                //产品序号
                DataTable dtProductNo = new DataTable();
                dtProductNo.Columns.Add("ContainerID");
                dtProductNo.Columns.Add("ContainerName");
                dtProductNo.Columns.Add("ProductNo");

                TemplatedColumn temCell1 = (TemplatedColumn)wgProductNoList.Columns.FromKey("ckSelect");

                int intQty = 0;
                for (int i = 0; i < temCell1.CellItems.Count; i++)
                {
                    Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[i];
                    CheckBox ckSelect = (CheckBox)cellItem1.FindControl("ckSelect");

                    if (ckSelect.Checked == true)
                    {
                        intQty++;

                        DataRow row = dtProductNo.NewRow();

                        if (wgProductNoList.Rows[i].Cells.FromKey("ContainerID").Value != null)
                        {
                            row["ContainerID"] = wgProductNoList.Rows[i].Cells.FromKey("ContainerID").Value.ToString();
                        }
                        else
                        {
                            row["ContainerID"] = string.Empty;
                        }

                        if (wgProductNoList.Rows[i].Cells.FromKey("ContainerName").Value != null)
                        {
                            row["ContainerName"] = wgProductNoList.Rows[i].Cells.FromKey("ContainerName").Value.ToString();
                        }
                        else
                        {
                            row["ContainerName"] = string.Empty;
                        }

                        if (wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value != null)
                        {
                            row["ProductNo"] = wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value.ToString();
                        }
                        else
                        {
                            row["ProductNo"] = string.Empty;
                        }

                        dtProductNo.Rows.Add(row);
                    }
                }

                if (intQty==0)
                {
                    ShowStatusMessage("子批次数量不能为0", false);
                    return;
                }

                if (intQty >= int.Parse(txtDispContainerQty.Text))
                {
                    ShowStatusMessage("子批次数量须小于主批次数量", false);
                    return;
                }

                //拆批
                Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
                string strOprEmployeeID = userInfo["EmployeeID"];
                string strEmployeeName = userInfo["EmployeeName"];
                string strPassword = userInfo["Password"];
                string strContainerName = txtDispContainerName.Text;
                string strNewContainerName = txtNewContainerName.Text.Trim();
                Dictionary<string, object> para1 = new Dictionary<string, object>();
                para1.Add("ContainerName", strContainerName);
                para1.Add("ServerUser", strEmployeeName);
                para1.Add("ServerPassword", strPassword);

                DataTable dtToContainerInfo = new DataTable();
                dtToContainerInfo.Columns.Add("ToContainerName");
                dtToContainerInfo.Columns.Add("Qty");
                dtToContainerInfo.Columns.Add("PlannedStartDate");
                dtToContainerInfo.Columns.Add("PlannedCompletionDate");

                DataRow rowToContainer = dtToContainerInfo.NewRow();
                rowToContainer["ToContainerName"] = strNewContainerName;
                rowToContainer["Qty"] = intQty.ToString();
                rowToContainer["PlannedStartDate"] = txtPlannedstartdate.Value;
                rowToContainer["PlannedCompletionDate"] = txtPlannedcompletiondate.Value;
                dtToContainerInfo.Rows.Add(rowToContainer);

                para1.Add("dtToContainerInfo", dtToContainerInfo);

                DataTable dtChildList = new DataTable();
                dtChildList.Columns.Add("ContainerName");
                dtChildList.Columns.Add("Level");

                foreach (DataRow r in dtProductNo.Rows)
                {
                    string strChild = r["ContainerName"].ToString();

                    if (strChild != string.Empty)
                    {
                        DataRow rr = dtChildList.NewRow();
                        rr["ContainerName"] = strChild;
                        rr["Level"] = "Lot";
                        dtChildList.Rows.Add(rr);
                    }
                }

                para1.Add("dtChildList", dtChildList);

                string strMessage = string.Empty;

                Boolean result;
                if (hdSuccess.Value == "")
                {
                    result = rejectapp.SplitContainer(para1, out strMessage);

                    if (result == false)
                    {
                        ShowStatusMessage(strMessage, false);
                        return;
                    }
                    hdSuccess.Value = "Success";
                }
                if (hdSuccess.Value == "Success")
                {
                    //修改批次计划开始结束时间
                    result = rejectapp.ContainerMaint(para1, ref strMessage);

                    if (result == false)
                    {
                        ShowStatusMessage(strMessage, false);
                        return;
                    }
                }

            }
            Session["ContainerMessage"] = "批次拆分成功！";
            Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");

            #region 记录日志
          var  userInfo2 = Session["UserInfo"] as Dictionary<string, string>;
            var ml = new MESAuditLog();
            ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
            ml.ParentID = txtDispContainerID.Text; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo2["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 1;
            ml.Description = "批次拆分:" +splitContainers;
            common.SaveMESAuditLog(ml);
            #endregion

        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string strTime = (int.Parse(txtTime.Text) + wgChildContainers.Rows.Count).ToString();
        wgChildContainers.Rows.Add();
        if (txtLevel.Text == "1")
        {
            wgChildContainers.Rows[wgChildContainers.Rows.Count-1].Cells.FromKey("ContainerName").Text = txtDispContainerName.Text + "-" + strTime.PadLeft(2, '0');
        }

        if (txtLevel.Text == "2")
        {
            wgChildContainers.Rows[wgChildContainers.Rows.Count - 1].Cells.FromKey("ContainerName").Text = txtDispContainerName.Text + "-" + strTime;
        }

        if (txtLevel.Text == "3")
        {
            char a = (char)(int.Parse(strTime) - 1 + 65);
            wgChildContainers.Rows[wgChildContainers.Rows.Count - 1].Cells.FromKey("ContainerName").Text = txtDispContainerName.Text + a;
        }
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        TemplatedColumn temCell1 = (TemplatedColumn)wgChildContainers.Columns.FromKey("ckSelect");

        for (int i = temCell1.CellItems.Count - 1; i >= 0; i--)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem1.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                wgChildContainers.Rows.RemoveAt(i);
            }
        }
    }
}